package com.orhon.smartcampus.modules.teacher.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.teacher.dao.ForeignLanguagesDao;
import com.orhon.smartcampus.modules.teacher.dao.TInformationDao;
import com.orhon.smartcampus.modules.teacher.entity.ForeignLanguages;
import com.orhon.smartcampus.modules.teacher.gqlInputModel.GQLForeignLanguagesInput;
import com.orhon.smartcampus.modules.teacher.inputMapper.ForeignLanguagesInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddForeignLanguagesMutation implements DataFetcher {

    @Autowired
    ForeignLanguagesDao foreignLanguagesDao;

    @Autowired
    TInformationDao tInformationDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;


    /**
     * 添加外语信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);
        GQLForeignLanguagesInput input = ForeignLanguagesInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        ForeignLanguages foreignLanguages = null;

        if (input.getId() != null) {
            foreignLanguages = foreignLanguagesDao.get(ForeignLanguages.class, input.getId());
            foreignLanguages.setUpdatedAt(new Date());
        } else {
            foreignLanguages = new ForeignLanguages();
            foreignLanguages.setCreatedAt(new Date());
        }
        if(schoolId != null){

            foreignLanguages.setSchool_id(schoolId);
        }
        if(input.getTeacher_id() != null){

            foreignLanguages.setTeacher_id(input.getTeacher_id());
        }
        if(input.getImage() != null){

            foreignLanguages.setImage(input.getImage());
        }
        if(input.getShenhe() != null){

            foreignLanguages.setShenhe(input.getShenhe());
        }
        if(input.getNames() != null){

            foreignLanguages.setNames((String) input.getNames());
        }
        if(input.getLanguelevel() != null){

            foreignLanguages.setLanguelevel(JSON.toJSONString(input.getLanguelevel()));
        }
        try{
            foreignLanguagesDao.saveOrUpdate(foreignLanguages);
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }
}

